package com.emm.yixun.mobile.adapter;

import android.app.Activity;
import android.content.Intent;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.demo.utils.PathUtils;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.FollowUpAdapter.RecordInfo.RecordList;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.model.GetFollowList;
import com.emm.yixun.mobile.model.GetFollowList.FollowList;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.yixun.app.viewpagerandimag.sample.ViewPagerActivity;

import java.io.File;
import java.util.ArrayList;

import xf.tools.Loading;

public class FollowUpAdapter extends BaseAdapter {

    Activity a;
    GetFollowList list;
    int type;// 1 详情 2跟进

    public FollowUpAdapter(Activity a, GetFollowList list, int type) {
        this.a = a;
        this.list = list;
        this.type = type;
    }

    /**
     * 获取新数据并刷新
     */
    public void SetDeta(ArrayList<FollowList> followList) {
        if (null == this.list.getFollowList()) {
            ArrayList<FollowList> a = new ArrayList<GetFollowList.FollowList>();
            this.list.setFollowList(a);
        }
        this.list.getFollowList().addAll(0, followList);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return list.getFollowList() == null ? 0 : list.getFollowList().size();
    }

    @Override
    public Object getItem(int position) {
        return list.getFollowList() == null ? null : list.getFollowList().get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHoudler v = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(a).inflate(R.layout.followup_item, null);
            v = new ViewHoudler();
            v.content_time = (TextView) convertView.findViewById(R.id.content_time);
            v.follow_type = (TextView) convertView.findViewById(R.id.follow_type);
            v.open_image = (ImageView) convertView.findViewById(R.id.open_image);
            v.open_video_pm = (ImageView) convertView.findViewById(R.id.open_video_pm);
            v.pir_linear = (LinearLayout) convertView.findViewById(R.id.pir_linear);
            v.pir_size = (TextView) convertView.findViewById(R.id.pir_size);
            v.text_content = (TextView) convertView.findViewById(R.id.text_content);
            v.video_linear = (LinearLayout) convertView.findViewById(R.id.video_linear);
            v.video_times = (TextView) convertView.findViewById(R.id.video_times);
            v.down_seekbar = (SeekBar) convertView.findViewById(R.id.down_seekbar);
            v.text_content_linear = (LinearLayout) convertView.findViewById(R.id.text_content_linear);
            convertView.setTag(v);
        } else {
            v = (ViewHoudler) convertView.getTag();
        }
        v.down_seekbar.setEnabled(false);
        try {
            // ：1、文本；2、图片；3、语音 N
            if ("1".equals(list.getFollowList().get(position).getFollowType())) {
                v.text_content_linear.setVisibility(View.VISIBLE);
                v.video_linear.setVisibility(View.GONE);
                v.pir_linear.setVisibility(View.GONE);

                v.text_content.setText(Html.fromHtml(list.getFollowList().get(position).getContentList().get(0)
                        .getFollowContent()));
            } else if ("3".equals(list.getFollowList().get(position).getFollowType())) {
                v.text_content_linear.setVisibility(View.GONE);
                v.video_linear.setVisibility(View.VISIBLE);
                v.pir_linear.setVisibility(View.GONE);
                v.video_times.setText(list.getFollowList().get(position).getVoiceTime());
            } else {// if("2".equals(list.getFollowList().get(position).getFollowType()))
                v.text_content_linear.setVisibility(View.GONE);
                v.video_linear.setVisibility(View.GONE);
                v.pir_linear.setVisibility(View.VISIBLE);

                if (null != list.getFollowList().get(position).getContentList()) {
                    v.pir_size.setText("(" + list.getFollowList().get(position).getContentList().size() + ")");
                }
                EmmApplication.image(R.drawable.xq_img_new);
                EmmApplication.imageLoader.displayImage(list.getFollowList().get(position).getContentList().get(0)
                        .getFollowContent(), v.open_image, EmmApplication.options);
            }

            v.content_time.setText(list.getFollowList().get(position).getFollowTime());
            v.follow_type.setText(list.getFollowList().get(position).getFollowMode());

            v.open_image.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    ViewPagerActivity.postion = 0;
                    ViewPagerActivity.sDrawables.clear();
                    for (int u = 0; u < list.getFollowList().get(position).getContentList().size(); u++) {
                        ViewPagerActivity.sDrawables.add(list.getFollowList().get(position).getContentList().get(u)
                                .getFollowContent());
                    }
                    Intent intent = new Intent(a, ViewPagerActivity.class);
                    a.startActivity(intent);
                }
            });

            final ImageView image = v.open_video_pm;
            final SeekBar seekbar = v.down_seekbar;
            v.open_video_pm.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    String p1 = null;
                    if (null != list.getFollowList().get(position).getVoiceLocalAddr()) {
                        p1 = list.getFollowList().get(position).getVoiceLocalAddr();
                    } else {
                        EmmApplication.Ts("没有找到该语音");
                        return;
                    }
                    String patch = PathUtils.Companion.getVideoFile(a).getPath();
                    String mp3url = "";
                    if (null != list.getFollowList().get(position).getContentList()
                            && list.getFollowList().get(position).getContentList().size() > 0) {
                        mp3url = list.getFollowList().get(position).getContentList().get(0).getFollowContent();
                    } else {// 如果不存在下载链接，需要提示
                        EmmApplication.Ts("没有找到该语音");
                        return;
                    }
                    if ("play".equals(p1.substring(p1.length() - 4, p1.length()))) {// IOS的路径
                        p1 = patch + "/" + mp3url.substring(mp3url.length() - 12, mp3url.length());
                    }
                    if ("wav".equals(p1.substring(p1.length() - 3, p1.length()))
                            || "WAV".equals(p1.substring(p1.length() - 3, p1.length()))) {
                        p1 = patch + "/" + mp3url.substring(mp3url.length() - 12, mp3url.length());
                    }
                    File file = new File(p1);
                    if (!file.exists()) {
                        // 本地不存在,需要先下载
                        Log.v("录音适配器", "该录音本地不存在,需要下载");
                        try {
                            downloadAudio(
                                    list.getFollowList().get(position).getContentList().get(0).getFollowContent(),
                                    p1.substring(patch.length() + 1, p1.length() - 4), seekbar);
                        } catch (NullPointerException e) {
                            EmmApplication.Ts("没有找到该语音");
                            e.printStackTrace();// 打印错误日志
                            return;
                        }
                    } else {
                        // 本地存在
                        Log.v("录音适配器", "该录音本地存在");
                        EmmApplication.OpenPath = new File(p1);
                        if (type == 1) {
                            a.sendBroadcast(new Intent(EmmApplication.SendOpenVideo2));
                        } else {
                            a.sendBroadcast(new Intent(EmmApplication.SendOpenVideo));
                        }
                        EmmApplication.Select_position = position;
                    }
                }
            });
        } catch (NullPointerException e) {
            Log.v("--->", "跟进列表空指针异常");
            e.printStackTrace();
        }
        return convertView;
    }

    /**
     * 解析电话数据json串
     */
    private ArrayList<RecordList> GetJson(String json) {
        RecordInfo rdl;
        json = "\"recordList\":" + "\"" + json + "\"";
        JSONObject jsonObj = JSONObject.parseObject(json);
        rdl = JSONObject.parseObject(jsonObj.toString(), RecordInfo.class);
        return rdl.getRecordList();
    }

    public static class ViewHoudler {
        /**
         * 文本内容
         */
        TextView text_content;

        /**
         * 录音内容
         */
        LinearLayout video_linear;

        /**
         * 播放录音
         */
        ImageView open_video_pm;

        /**
         * 图片类容
         */
        LinearLayout pir_linear;

        /**
         * 录音时间
         */
        TextView video_times;

        /**
         * 打开图片预览
         */
        ImageView open_image;

        /**
         * 图片数量
         */
        TextView pir_size;

        /**
         * 跟进时间
         */
        TextView content_time;

        /**
         * 跟进类型
         */
        TextView follow_type;

        SeekBar down_seekbar;

        /**
         * 文本内容布局模块
         */
        LinearLayout text_content_linear;

    }

    /**
     * 从网络下载录音
     */
    private void downloadAudio(String url, String name, final SeekBar seekbar) {
        Log.w("下载链接", url);
        String endType = url.toString().substring(url.toString().length() - 3, url.toString().length());
        if ("aac".equals(endType)) {
            name = name + ".aac";
        }
        if ("mp3".equals(endType)) {
            name = name + ".mp3";
        }
        if ("pcm".equals(endType)) {
            name = name + ".pcm";
        }
        if ("WAV".equals(endType) || "wav".equals(endType)) {
            name = name + ".wav";
        }
        File vFile = new File(PathUtils.Companion.getVideoFile(a).getPath(), name);
        if (vFile.exists()) {
            vFile.delete();
        } else {
            File vDirPath = vFile.getParentFile();
            vDirPath.mkdirs();
        }
        String localFilePath = vFile.getPath();// 包括文件名
        Loading.hideDialogForLoading();
        Loading.showDialogForLoading(a, "加载录音...", false, true, 60000);
        HttpUtils http = new HttpUtils();
        HttpHandler handler = http.download(url, localFilePath, true, false, new RequestCallBack<File>() {
            @SuppressWarnings("deprecation")
            @Override
            public void onStart() {
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                // 总进度 total 当前进度：current isUploading
                super.onLoading(total, current, isUploading);
                Loading.SetTextViewContent("加载录音..." + ((current * 100) / total) + "%");
                Log.w("录音适配器", "下载进度：" + ((current * 100) / total) + "%");
                Log.w("录音适配器", "下载进度：" + current + "---total---" + total);
                seekbar.setProgress((int) ((current / total) * 100));
            }

            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                String urlAudio = responseInfo.result.getPath();
                Log.w("录音适配器", "下载完成，路径：" + urlAudio);
                EmmApplication.OpenPath = new File(urlAudio);
                if (type == 1) {
                    a.sendBroadcast(new Intent(EmmApplication.SendOpenVideo2));
                } else {
                    a.sendBroadcast(new Intent(EmmApplication.SendOpenVideo));
                }
                Loading.hideDialogForLoading();
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.w("录音适配器", "下载失败:" + error.getMessage() + "---msg--->" + msg);
                Loading.hideDialogForLoading();
            }
        });
    }

    public static class RecordInfo {


        ArrayList<RecordList> recordList;

        public ArrayList<RecordList> getRecordList() {
            return recordList;
        }

        public void setRecordList(ArrayList<RecordList> recordList) {
            this.recordList = recordList;
        }

        public static class RecordList {

            private String recordUrl;
            private String billableSeconds;

            public String getRecordUrl() {
                return recordUrl;
            }

            public void setRecordUrl(String recordUrl) {
                this.recordUrl = recordUrl;
            }

            public String getBillableSeconds() {
                return billableSeconds;
            }

            public void setBillableSeconds(String billableSeconds) {
                this.billableSeconds = billableSeconds;
            }

        }
    }
}
